package logic

import (
	"context"
	"fmt"
	"users/model/mysql"
	"users/model/redis"

	"users/userrpc/internal/svc"
	"users/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("smsLogin" + in.Phone)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("验证码输入错误")
	}
	var find mysql.User
	err := find.GetUser(in.Phone)
	if err != nil {
		logx.Error("该手机号码没有注册")
		return nil, err
	}

	if find.ID == 0 {
		user := mysql.User{
			Phone: in.Phone,
		}
		err = user.Create()
		if err != nil {
			logx.Error("注册失败")
			return nil, err
		}
		return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
	} else {
		return &userrpc.UserLoginResponse{Id: int64(find.ID)}, nil
	}

}
